import javax.swing.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.*;
import java.net.Socket;
import java.util.HashSet;
import java.util.concurrent.atomic.AtomicReference;

public class LoginWindow extends JFrame implements ActionListener {
    public Socket p ;
    public DatePacket d ;
    OutputStream outputStream;
    InputStream inputStream;
    private JLabel qqLogoLabel = new JLabel(new ImageIcon("src/图片1.jpg")); // 替换为你的QQ Logo图片路径
    private JLabel usernameLabel = new JLabel("账号:");
    private JTextField usernameField = new JTextField(20);
    private JLabel passwordLabel = new JLabel("密码:");
    private JPasswordField passwordField = new JPasswordField(20);
    private JButton loginButton = new JButton("登录");
    private JButton registerButton = new JButton("注册");
    public int strtoint(String i){
        int w = 0;
        char[] a = i.toCharArray();
        for(int j = 0;j<i.length() ;j++){


            if(a[j] < '0' ||a[j] > '9'){
                JOptionPane.showMessageDialog(this,"账号应全为数字");
                break;
            }else {
                w = (a[j] - 48 ) + w*10;
            }
        }
        return  w ;
    }
    @Override
    public void actionPerformed(ActionEvent e) {
        try {
            if (e.getSource() == loginButton) {
                String username = usernameField.getText();
                d.passward = new String(passwordField.getPassword());
                // 处理登录逻辑，例如验证用户名和密码。
                d.account = strtoint(username);
                d.direct = 8;
                try {
                    ObjectOutputStream objectOutputStream = new ObjectOutputStream(outputStream);
                    objectOutputStream.writeObject(d);
                    ObjectInputStream ois = new ObjectInputStream(inputStream);
                    d = (DatePacket) ois.readObject();
                } catch (IOException ex) {
                    throw new RuntimeException(ex);
                } catch (ClassNotFoundException ex) {
                    throw new RuntimeException(ex);
                }
                if (d.direct == 8) {
                    dispose();
                    try {
                        HashSet<Youyou> qing = new HashSet<>();
                        for (Roompower i : d.rooms) {
                            Youyou ii = new Youyou();

                            ii.room = i.room;
                            ii.chao = new SimpleChatInterface(p, d, outputStream, i);
                            qing.add(ii);
                        }
                        AtomicReference<ChatPanel> ds = new AtomicReference<>(new ChatPanel(p, d, outputStream, qing));
                        // 创建线程用于从服务器接收数据并展示给用户
                        Thread receiverThread = new Thread(() -> {
                            while (true) {
                                try {
                                    DatePacket ddd;
                                    try {
                                        ddd=new DatePacket();
                                        ObjectInputStream ois = new ObjectInputStream(inputStream);
                                        ddd = (DatePacket) ois.readObject();
                                    }catch (ClassNotFoundException ye) {
                                        System.out.println("反序列化失败！");
                                        throw new RuntimeException(ye);
                                    }
                                    switch (ddd.direct) {
                                        case 1: {
                                            JOptionPane.showMessageDialog(this, "创建成功，房间号为" + ddd.room);
                                            d.rooms = ddd.rooms;
                                            Youyou jing = new Youyou();
                                            jing.room = ddd.room;
                                            Roompower i = new Roompower();
                                            i.room = ddd.room;
                                            i.power = 1;
                                            i.roomname = ddd.roomname;
                                            jing.chao = new SimpleChatInterface(p, d, outputStream, i);
                                            qing.add(jing);
                                            ds.get().end();
                                            ds.set(new ChatPanel(p, d, outputStream, qing));
                                            break;
                                        }

                                        case 2: {
                                            JOptionPane.showMessageDialog(this, "加入成功");
                                            //System.out.println(ddd.rooms);
                                            d.rooms = ddd.rooms;
                                            Youyou jing = new Youyou();
                                            jing.room = ddd.room;
                                            Roompower i = new Roompower();
                                            i.room = ddd.room;
                                            i.power = 0;
                                            i.roomname = ddd.roomname;
                                            jing.chao = new SimpleChatInterface(p, d, outputStream, i);
                                            qing.add(jing);
                                            ds.get().end();
                                            ds.set(new ChatPanel(p, d, outputStream, qing));
                                            break;
                                        }
                                        case 3: {
                                            for (Roompower I : d.rooms) {
                                                if (I.room == ddd.room) {
                                                   // JOptionPane.showMessageDialog(this, "收到来自房间:  " + I.roomname + "  的新消息");
                                                    for (Youyou II : qing) {
                                                        if(II.room==ddd.room) {
                                                            II.chao.chatArea.append(ddd.name + "：" + ddd.message + "\n");
                                                            break;
                                                        }
                                                    }
                                                }
                                            }
                                            break;
                                        }
                                        case 4: {
                                            JOptionPane.showMessageDialog(this, "退出成功");
                                            d.rooms = ddd.rooms;
                                            Youyou ii = null;
                                            for (Youyou yi : qing) {

                                                if (yi.room == ddd.room) {
                                                    ii = yi;

                                                }
                                            }
                                            ii.chao.end();
                                            ds.get().end();
                                            ds.set(new ChatPanel(p, d, outputStream, qing));
                                            break;
                                        }
                                        case 5: {
                                            JOptionPane.showMessageDialog(this, "销毁成功");
                                            d.rooms = ddd.rooms;
                                            Youyou ii = null;
                                            for (Youyou yi : qing) {

                                                if (yi.room == ddd.room) {
                                                    ii = yi;

                                                }
                                            }
                                            ii.chao.end();
                                            ds.get().end();
                                            ds.set(new ChatPanel(p, d, outputStream, qing));
                                            break;
                                        }
                                        case 6:
                                        case 7: {
                                            JOptionPane.showMessageDialog(this, "修改成功");
                                            break;
                                        }
                                        case 101:{
                                            JOptionPane.showMessageDialog(this, "创建失败，请稍后再试");
                                        }
                                        case 102: {
                                            JOptionPane.showMessageDialog(this, "加入失败" + ddd.message);
                                            break;
                                        }
                                        case 103: {
                                            JOptionPane.showMessageDialog(this, "发送失败");
                                            break;
                                        }
                                        case 104:{
                                            JOptionPane.showMessageDialog(this, "退出失败，请稍后再试");
                                            break;
                                        }
                                        case 105:{
                                            JOptionPane.showMessageDialog(this, "销毁失败，请稍后再试");
                                            break;
                                        }
                                        default:
                                            //JOptionPane.showMessageDialog(this, "操作失败");
                                            break;
                                    }


                                }catch(StreamCorruptedException t){
                                    t.printStackTrace();
                                }
                                catch (IOException aa) {
                                    aa.printStackTrace();
                                }
                            }
                        });
                        receiverThread.start();

                    } catch (Exception mm) {
                        mm.printStackTrace();
                    }
                } else {
                    JOptionPane.showMessageDialog(this, d.message);
                }
            } else if (e.getSource() == registerButton) {
                // 打开注册窗口。你可以在这里隐藏当前窗口并显示注册窗口。
                dispose();// 隐藏当前窗口。
                new QQRegisterWindow(p, d,outputStream,inputStream); // 显示注册窗口。请确保你已经定义了QQRegisterWindow类。
            }
        } finally {

        }
    }
public LoginWindow (Socket p,DatePacket d,OutputStream outputStream,InputStream inputStream){
        this.p = p;
        this.d = d;
        this.outputStream=outputStream;
        this.inputStream=inputStream;
    setTitle("登录");
    setSize(400, 600); // 调整窗口大小以适应你的设计需求
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    setResizable(false);
    setVisible(true);
    setLocationRelativeTo(null); // 窗口居中显示
    // 设置布局为null，以便自定义组件位置
    setLayout(null);
    // 设置组件的位置和大小（这里只是示例，你可以根据自己的需求调整）
    qqLogoLabel.setBounds(120, 20, 160, 160); // 设置QQ Logo的位置和大小
    usernameLabel.setBounds(60, 200, 60, 30);
    usernameField.setBounds(120, 200, 200, 30);
    passwordLabel.setBounds(60, 240, 60, 30);
    passwordField.setBounds(120, 240, 200, 30);
    loginButton.setBounds(140, 280, 80, 30);
    registerButton.setBounds(240, 280, 80, 30);
    // 将组件添加到窗口中
    add(qqLogoLabel);
    add(usernameLabel);
    add(usernameField);
    add(passwordLabel);
    add(passwordField);
    add(loginButton);
    add(registerButton);
    // 添加事件监听器
    loginButton.addActionListener(this);
    registerButton.addActionListener(this);
}
}